package cn.pconline.autoclub.service;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.Comment;
import cn.pconline.autoclub.entity.User;
import cn.pconline.passport2.util.T;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;

/**
 * 审核服务类
 */
public class CensorCommentService extends CensorService {

    // 留言typeId,在bean初始化的时候赋值
    private long typeIdComment;
    @Autowired
    private ClubService clubService;

    public void setTypeIdComment(long typeIdComment) {
        this.typeIdComment = typeIdComment;
    }

    /**
     * 审核应用回馈
     *
     * @param interfaceUrl
     * @param url
     * @param status
     * @param version
     * @return
     */
    public String feedback(String interfaceUrl, String url, int status,
            long version) {

        String result = null;
        // url must format like : http://club.pcauto.com.cn/gzqrcyh/comment/?typeId=100&clubId=200&commentId=300
        
        Map<String,Long> map  = getMapByUrl(url);
        long id = map.get("commentId");
        long clubId = map.get("clubId");
        long typeId = map.get("typeId");
        if (typeId == typeIdComment) {
            Comment comment = null;
            try {
				comment = geliDao.find(Comment.class, clubId, id);
			} catch (DataAccessException e) {
				
				log.info("审核平台回调留言已不存在:"+id);
			}
            if (comment!=null &&(version == comment.getUpdateDate().getTime())) {
                int commentStatus = comment.getCensored();
                switch (status) {
                    //审核通过?
                    case CENSORSYSTEM_RESPONSE_PASS:
                        if (commentStatus == Comment.CENSORED_NOCAREFUL) {
                            comment.setCensored(Comment.CENSORED_NORMAL);
                            this.geliDao.update(comment, "censored");
                        }
                        break;
                    //审核不通过    
                    case CENSORSYSTEM_RESPONSE_DENY:
                        comment.setStatus(Comment.STATUS_DELETE);
                        comment.setCensored(Comment.CENSORED_DELETE);
                        this.geliDao.update(comment, "censored,status");
                        log.info("车友会留言审核未通过：" + id);
                        break;
                    default:
                        result = "状态不正确";
                        break;
                }
            }
        }

        return result;
    }

    /**
     * 发留言时,首次通知审核平台新建留言状态
     *
     * @param request
     * @param comment
     */
    public void notifyCensorSystemCreate(HttpServletRequest request, final Comment comment) {
        if (csr_switch) {
            final Map<String, Object> params = convert4Create(request, comment, true);
            executorService.submit(new CensorCall(receiveHome, params));
        }
    }

    /**
     * 发留言时,通知审核平台更新留言状态
     *
     * @param request
     * @param comment
     */
    public void notifyCensorSystemUpdate(HttpServletRequest request, final Comment comment) {
        if (csr_switch) {
            final Map<String, Object> params = convert4DeleteAndRestore(request, comment);
            executorService.submit(new CensorCall(statusChangeHome, params));
        }
    }

    /**
     * 将Comment类转换成向审核系统传递的参数,只用在新建留言时
     *
     * @param userProfile
     * @param isNew
     * @return
     */
    private Map<String, Object> convert4Create(HttpServletRequest request, Comment comment,
            boolean isNew) {
        User user = null;
        Club club = clubService.getClub(comment.getClubId());
        try {
            user = this.geliDao.find(User.class, comment.getCreateBy());
        } catch (DataAccessException e) {
        }
        Map<String, Object> map = new HashMap<String, Object>(16);
        //标题????????
        map.put(TITLE, comment.getContent());
        map.put(SITE, site);
        map.put(APP, appName);
        map.put(TYPEID, typeIdComment);
        map.put(ISNEW, isNew ? 1 : 0);
        // uri formate : "http://club.pcauto.com.cn/gzqrcyh/comment/?typeId=100&clubId=200&commentId=300";
        String root = "http://" + T.stringValue(request.getHeader("host"), "") + T.stringValue(request.getContextPath(), "");
        map.put(URI, root + "/" +club.getClubUrl()+"/comment/" + "?typeId="
                + typeIdComment + "&clubId=" + comment.getClubId()+"&commentId="+ comment.getCommentId());
        map.put(VERSION, (comment.getUpdateDate().getTime() / 1000) * 1000);
        map.put(USERID, user.getUid());
        map.put(USERNAME, user.getUsername());
        map.put(IP, T.getIp(request));
        map.put(CONTENT, comment.getContent());

        return map;
    }

    private Map<String, Object> convert4DeleteAndRestore(HttpServletRequest request, Comment comment) {
        Map<String, Object> map = new HashMap<String, Object>(6);
        User user = null;
        try {
            user = this.geliDao.find(User.class, comment.getCreateBy());
        } catch (DataAccessException e) {
        }
        map.put(APP, appName);
        String root = "http://" + T.stringValue(request.getHeader("host"), "") + T.stringValue(request.getContextPath(), "");
        map.put(URI, root + "/" + comment.getCommentId() + "?typeId="
                + typeIdComment);
        map.put(STATUS, CENSORSYSTEM_RESPONSE_DENY);
        //应用对内容的更新时间，需要转化为毫秒进行传输
        map.put(UPDATEAT, (comment.getUpdateDate().getTime() / 1000) * 1000);
        map.put(USERID, user == null ? " " : user.getUid());
        map.put(USERNAME, user == null ? " " : user.getUsername());
        return map;
    }

    @Override
    public boolean isCorrectFeedback(String url) {
    	Map<String,Long> map  = getMapByUrl(url);
    	long typeId = 0;
    	if(map!=null&&!map.isEmpty()){
    		typeId = map.get("typeId");
    	}
        return typeIdComment == typeId;
    }
}
